package com.yst.webplugin.loginplugin;

import com.yst.spring.context.SpringContext;
import com.yst.webplugin.exception.ExceptionNotLogin;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;


public abstract class UserUtils {
    public static Object getCurrentUserId(){
        IUserInfoProvider userInfoProvider= SpringContext.getContext()
                .getBean(IUserInfoProvider.class);
        return userInfoProvider.getUserId();
    }

    public static Long getUserIdAsLong(){
        return (Long) getCurrentUserId();
    }

    public static Integer getUserIdAsInteger(){
        return (int) getCurrentUserId();
    }

    public static void checkLogin(){
        if (Objects.isNull(getCurrentUserId())){
            throw new ExceptionNotLogin();
        }
    }


    public static void checkLogin(Field field){
        Class<?> clazz=field.getDeclaringClass();
        LoginCheck loginCheck=clazz.getAnnotation(LoginCheck.class);
        if (Objects.isNull(loginCheck)){
            loginCheck=field.getAnnotation(LoginCheck.class);
        }
        if (Objects.isNull(loginCheck)|| loginCheck.ignore()) return;
        try {
            if (Objects.nonNull(getCurrentUserId())) {
                return;
            }
        }
        catch (Exception ignore) {

        }
        throw new ExceptionNotLogin();
    }

    public static void checkLogin(Method method){
        Class<?> clazz=method.getDeclaringClass();
        LoginCheck loginCheck=clazz.getAnnotation(LoginCheck.class);
        if (Objects.isNull(loginCheck)) {
            loginCheck = method.getAnnotation(LoginCheck.class);
        }
        if (Objects.isNull(loginCheck)||loginCheck.ignore()) return;
        try {
            if (Objects.nonNull(getCurrentUserId())) {
                return;
            }
        }
        catch (Exception ignore){

        }
        throw new ExceptionNotLogin();
    }

}
